<?php
namespace app\common\only\jy;

class OrderProduct extends Base {
	protected $prefix = 'jy\\OrderProduct';

	//根据订单id获取订单产品
	public function refund4oid($oid) {
		$model = $this->getModel('jy\\OrderProduct');

		return $this->get('refund4oid_' . $oid, function($model, $oid){
			return $model->where(['oid' => $oid])->column('id,psid,num,snapshotid');
		}, [$model, $oid]);
	}

	//退款单是否支持退货
	public function isReturnProducts4refund($orid) {
		return $this->get('isReturnProducts4refund_' . $orid, function($only, $orid) {
			$isReturn = false;
			$retund = $only->getModel('jy\\OrderRefund')->find($orid);
			if(empty($retund)) {
				throw new \Exception('退款单不存在');
			}
			$oid = $retund['oid'];
			$order = $only->getModel('jy\\Order')->find($oid);
			if($order['status'] == loadEnum('OrderStatus')->code2key('daifahuo') || $order['status'] == loadEnum('OrderStatus')->code2key('daiziti')) {
				return $isReturn;
			}
			$opids = $only->getModel('jy\\OrderRefundProduct')->where(['orid' => $orid])->column('opid');
			foreach ($opids as $k => $opid) {
				if($this->isReturnProducts($opid)) {
					$isReturn = true;
					break;
				}
			}
			return $isReturn;
		}, [$this, $orid]);
	}

	//是否支持退货
	public function isReturnProducts($opid) {
		$enum = loadEnum('OstSale');

		$row = $this->find('jy\\OrderProduct', $opid);
		if(empty($row)) {
			throw new \Exception('订单产品不存在');
		}
		$snapshot = $this->find('jy\\SnapshotProduct', $row['snapshotid']);
		if(empty($snapshot)) {
			throw new \Exception('快照不存在');
		}
		return $enum->isReturn($snapshot['osid']); 
	}
}